package com.hlm.web.controller;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.util.Date;

//这个是使用jwt
@Controller
public class TokenLoginController2 {
    @Autowired
    private StringRedisTemplate template;
    //    登录生成token
    @RequestMapping("/login2")
    public ModelAndView login() {
        String token = JWT.create()
//                设置过期时间
                .withExpiresAt(new Date(System.currentTimeMillis() + 10000))
//                设置接受方信息，一般时登录用户
                .withAudience("user1")
//                使用HMAC256算法 生成token，密钥是12345
                .sign(Algorithm.HMAC256("12345"));
        System.out.println(token);

//        try {
//            Thread.sleep(11000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
// TODO: 2020/7/9 token存到redis
        ValueOperations<String,String> ops =template.opsForValue();
        ops.set("user1" , token);
        System.out.println("redis数据"+ops.get("user1"));
//        验证
        if(verify(token)){  //如果验证成功
//            返回20220
            ModelAndView mv = new ModelAndView("redirect:http://192.168.0.158:20220/#");
        System.out.println(mv.toString());
            return mv;
        }
//        如果验证失败
//        返回一个错误页面
        return new ModelAndView("verifyerror");
    }

//    验证逻辑
    public static boolean verify(String token){
        try{
//            验证失败会catch 异常
            JWT.require(Algorithm.HMAC256("12345")).build().verify(token);
            return true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }
    @GetMapping("/test")
    public String error(){
        System.out.println("test接口访问了");
        return "/verifyerror";
    }

}
